<template>
  <div v-if="show" class="modal-mask" @click.self="closeModal">
    <div class="modal-container">
      <div class="modal-header">
        <h2>{{ currentTab === 'login' ? '用户登录' :
            currentTab === 'register' ? '新用户注册' :
                currentTab === 'forgot' ? '找回密码' : '邮箱登录' }}</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>

      <div class="modal-body">
        <!-- 登录/注册/找回密码切换标签 -->
        <div class="tab-switch">
          <button
              v-for="tab in tabs"
              :key="tab.value"
              :class="{ active: currentTab === tab.value }"
              @click="switchTab(tab.value)"
          >
            {{ tab.label }}
          </button>
        </div>

        <!-- 登录表单 -->
        <form v-if="currentTab === 'login'" @submit.prevent="handleLogin">
          <div class="form-group">
            <label>用户名/邮箱:</label>
            <input
                v-model="loginForm.username"
                type="text"
                placeholder="请输入用户名或邮箱"
                :class="{ 'input-error': loginErrors.username }"
            />
            <span v-if="loginErrors.username" class="error-msg">{{ loginErrors.username }}</span>
          </div>

          <div class="form-group">
            <label>密码:</label>
            <input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :class="{ 'input-error': loginErrors.password }"
            />
            <span v-if="loginErrors.password" class="error-msg">{{ loginErrors.password }}</span>
          </div>

          <div class="form-group">
            <label>验证码:</label>
            <div style="display: flex">
              <div style="flex: 2">
                <input
                    v-model="loginForm.code"
                    type="text"
                    placeholder="请输入验证码"
                    :class="{ 'input-error': loginErrors.code }"
                />
                <span v-if="loginErrors.code" class="error-msg">{{ loginErrors.code }}</span>
              </div>
              <div style="flex: 1;margin-left: 15px">
                <el-image style="width: 120px;height: 42px;" :src="captchaUrl" @click="refreshCaptcha" alt="验证码" class="captcha-img" />
              </div>
            </div>
          </div>

          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" v-model="loginForm.remember" /> 记住我
            </label>
            <a href="#" @click.prevent="switchTab('forgot')">忘记密码?</a>
          </div>

          <div class="form-actions">
            <button
                type="submit"
                class="submit-btn"
                :disabled="isLoggingIn"
            >
              {{ isLoggingIn ? '登录中...' : '立即登录' }}
            </button>
          </div>
        </form>

        <!-- 注册表单 -->
        <form v-if="currentTab === 'register'" @submit.prevent="handleRegister">
          <div class="form-group">
            <label>用户名:</label>
            <input
                v-model="registerForm.username"
                type="text"
                placeholder="请输入用户名"
                :class="{ 'input-error': registerErrors.username }"
            />
            <span v-if="registerErrors.username" class="error-msg">{{ registerErrors.username }}</span>
          </div>

          <div class="form-group">
            <label>邮箱:</label>
            <div class="input-with-btn">
              <input
                  v-model="registerForm.email"
                  type="email"
                  placeholder="请输入邮箱"
                  :class="{ 'input-error': registerErrors.email }"
              />
              <button
                  type="button"
                  class="get-code-btn"
                  :disabled="isGettingCode || codeCountdown > 0"
                  @click="getVerificationCode('register')"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s后重新获取` : '获取验证码' }}
              </button>
            </div>
            <span v-if="registerErrors.email" class="error-msg">{{ registerErrors.email }}</span>
          </div>

          <div class="form-group">
            <label>验证码:</label>
            <input
                v-model="registerForm.code"
                type="text"
                placeholder="请输入验证码"
                :class="{ 'input-error': registerErrors.code }"
            />
            <span v-if="registerErrors.code" class="error-msg">{{ registerErrors.code }}</span>
          </div>

          <div class="form-group">
            <label>密码:</label>
            <input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                :class="{ 'input-error': registerErrors.password }"
            />
            <span v-if="registerErrors.password" class="error-msg">{{ registerErrors.password }}</span>
          </div>

          <div class="form-group">
            <label>确认密码:</label>
            <input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                :class="{ 'input-error': registerErrors.confirmPassword }"
            />
            <span v-if="registerErrors.confirmPassword" class="error-msg">{{ registerErrors.confirmPassword }}</span>
          </div>

          <div class="form-actions">
            <button
                type="submit"
                class="submit-btn"
                :disabled="isRegistering"
            >
              {{ isRegistering ? '注册中...' : '立即注册' }}
            </button>
          </div>
        </form>

        <!-- 找回密码表单 -->
        <form v-if="currentTab === 'forgot'" @submit.prevent="handleForgotPassword">
          <div class="form-group">
            <label>邮箱:</label>
            <div class="input-with-btn">
              <input
                  v-model="forgotForm.email"
                  type="email"
                  placeholder="请输入注册邮箱"
                  :class="{ 'input-error': forgotErrors.email }"
              />
              <button
                  type="button"
                  class="get-code-btn"
                  :disabled="isGettingCode || codeCountdown > 0"
                  @click="getVerificationCode('forgot')"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s后重新获取` : '获取验证码' }}
              </button>
            </div>
            <span v-if="forgotErrors.email" class="error-msg">{{ forgotErrors.email }}</span>
          </div>

          <div class="form-group">
            <label>验证码:</label>
            <input
                v-model="forgotForm.code"
                type="text"
                placeholder="请输入验证码"
                :class="{ 'input-error': forgotErrors.code }"
            />
            <span v-if="forgotErrors.code" class="error-msg">{{ forgotErrors.code }}</span>
          </div>

          <div class="form-group">
            <label>新密码:</label>
            <input
                v-model="forgotForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                :class="{ 'input-error': forgotErrors.newPassword }"
            />
            <span v-if="forgotErrors.newPassword" class="error-msg">{{ forgotErrors.newPassword }}</span>
          </div>

          <div class="form-actions">
            <button
                type="submit"
                class="submit-btn"
                :disabled="isResetting"
            >
              {{ isResetting ? '重置中...' : '重置密码' }}
            </button>
          </div>
        </form>

        <!-- 邮箱验证码登录 -->
        <form v-if="currentTab === 'emailLogin'" @submit.prevent="handleEmailLogin">
          <div class="form-group">
            <label>邮箱:</label>
            <div class="input-with-btn">
              <input
                  v-model="emailLoginForm.email"
                  type="email"
                  placeholder="请输入邮箱"
                  :class="{ 'input-error': emailLoginErrors.email }"
              />
              <button
                  type="button"
                  class="get-code-btn"
                  :disabled="isGettingCode || codeCountdown > 0"
                  @click="getVerificationCode('emailLogin')"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s后重新获取` : '获取验证码' }}
              </button>
            </div>
            <span v-if="emailLoginErrors.email" class="error-msg">{{ emailLoginErrors.email }}</span>
          </div>

          <div class="form-group">
            <label>验证码:</label>
            <input
                v-model="emailLoginForm.code"
                type="text"
                placeholder="请输入验证码"
                :class="{ 'input-error': emailLoginErrors.code }"
            />
            <span v-if="emailLoginErrors.code" class="error-msg">{{ emailLoginErrors.code }}</span>
          </div>

          <div class="form-actions">
            <button
                type="submit"
                class="submit-btn"
                :disabled="isEmailLoggingIn"
            >
              {{ isEmailLoggingIn ? '登录中...' : '立即登录' }}
            </button>
          </div>
        </form>

        <!-- 底部链接 -->
        <div class="form-footer">
          <template v-if="currentTab === 'login'">
            没有账号? <a href="#" @click.prevent="switchTab('register')">立即注册</a>
            <span class="divider">|</span>
            <a href="#" @click.prevent="switchTab('emailLogin')">邮箱验证码登录</a>
          </template>
          <template v-else-if="currentTab === 'register'">
            已有账号? <a href="#" @click.prevent="switchTab('login')">立即登录</a>
          </template>
          <template v-else-if="currentTab === 'forgot'">
            <a href="#" @click.prevent="switchTab('login')">返回登录</a>
          </template>
          <template v-else-if="currentTab === 'emailLogin'">
            <a href="#" @click.prevent="switchTab('login')">账号密码登录</a>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,reactive,onMounted } from 'vue'
import {codeCheckOk, getCheckCode, getEmailCode, login, register} from "@/api/acconut.js";
import { userInform} from "@/stores/userInform.js";
import { ElMessage } from 'element-plus'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})

const userInformPink = userInform()
const emit = defineEmits(['close', 'login-success', 'register-success'])

// 标签页管理
const tabs = [
  { label: '账号登录', value: 'login' },
  { label: '邮箱登录', value: 'emailLogin' },
  { label: '注册账号', value: 'register' },
  { label: '找回密码', value: 'forgot' }
]
const currentTab = ref('login')

const switchTab = (tab) => {
  currentTab.value = tab
  resetAllForms()
}

//获取验证码
const captchaUrl = ref('')
const refreshCaptcha = async () => {
  // 刷新验证码
  const res = await getCheckCode()
  captchaUrl.value = res.data.checkCode
  loginForm.cokeKey = res.data.checkCodeKey
}

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  cokeKey:'',
  remember: false
})

const loginErrors = reactive({
  username: '',
  password: ''
})

const isLoggingIn = ref(false)

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

const registerErrors = reactive({
  username: '',
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

const isRegistering = ref(false)

// 找回密码表单
const forgotForm = reactive({
  email: '',
  code: '',
  newPassword: ''
})

const forgotErrors = reactive({
  email: '',
  code: '',
  newPassword: ''
})

const isResetting = ref(false)

// 邮箱登录表单
const emailLoginForm = reactive({
  email: '',
  code: ''
})

const emailLoginErrors = reactive({
  email: '',
  code: ''
})

const isEmailLoggingIn = ref(false)

// 验证码相关
const isGettingCode = ref(false)
const codeCountdown = ref(0)

// 表单验证方法
const validateLoginForm = () => {
  let isValid = true
  loginErrors.username = ''
  loginErrors.password = ''

  if (!loginForm.username.trim()) {
    loginErrors.username = '请输入用户名或邮箱'
    isValid = false
  }

  if (!loginForm.password) {
    loginErrors.password = '请输入密码'
    isValid = false
  } else if (loginForm.password.length < 6) {
    loginErrors.password = '密码长度不能小于6位'
    isValid = false
  }

  return isValid
}

const validateRegisterForm = () => {
  let isValid = true
  registerErrors.username = ''
  registerErrors.email = ''
  registerErrors.code = ''
  registerErrors.password = ''
  registerErrors.confirmPassword = ''

  if (!registerForm.username.trim()) {
    registerErrors.username = '请输入用户名'
    isValid = false
  } else if (registerForm.username.length < 4) {
    registerErrors.username = '用户名长度不能小于4位'
    isValid = false
  }

  if (!registerForm.email) {
    registerErrors.email = '请输入邮箱'
    isValid = false
  } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(registerForm.email)) {
    registerErrors.email = '请输入有效的邮箱地址'
    isValid = false
  }

  if (!registerForm.code) {
    registerErrors.code = '请输入验证码'
    isValid = false
  }

  if (!registerForm.password) {
    registerErrors.password = '请输入密码'
    isValid = false
  } else if (registerForm.password.length < 6) {
    registerErrors.password = '密码长度不能小于6位'
    isValid = false
  }

  if (registerForm.password !== registerForm.confirmPassword) {
    registerErrors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }

  return isValid
}

const validateForgotForm = () => {
  let isValid = true
  forgotErrors.email = ''
  forgotErrors.code = ''
  forgotErrors.newPassword = ''

  if (!forgotForm.email) {
    forgotErrors.email = '请输入邮箱'
    isValid = false
  } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(forgotForm.email)) {
    forgotErrors.email = '请输入有效的邮箱地址'
    isValid = false
  }

  if (!forgotForm.code) {
    forgotErrors.code = '请输入验证码'
    isValid = false
  }

  if (!forgotForm.newPassword) {
    forgotErrors.newPassword = '请输入新密码'
    isValid = false
  } else if (forgotForm.newPassword.length < 6) {
    forgotErrors.newPassword = '密码长度不能小于6位'
    isValid = false
  }

  return isValid
}

const validateEmailLoginForm = () => {
  let isValid = true
  emailLoginErrors.email = ''
  emailLoginErrors.code = ''

  if (!emailLoginForm.email) {
    emailLoginErrors.email = '请输入邮箱'
    isValid = false
  } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(emailLoginForm.email)) {
    emailLoginErrors.email = '请输入有效的邮箱地址'
    isValid = false
  }

  if (!emailLoginForm.code) {
    emailLoginErrors.code = '请输入验证码'
    isValid = false
  }

  return isValid
}

// 表单提交处理
const handleLogin = async () => {
  if (!validateLoginForm()) return

    isLoggingIn.value = true
    //验证验证码
    const data = await codeCheckOk(loginForm)
    if(data.code !== 200) {
      isLoggingIn.value = false
      return ElMessage.error(data.message)
    }
    //正式登录
    const res = await login(loginForm)
    if(res.code !== 200) {
      isLoggingIn.value = false
      return ElMessage.error(res.message)
    }
    await userInformPink.setUserInformData(res.data.username)
    userInformPink.setToken(res.data.token)
    localStorage.setItem('token', res.data.token) // 写入Cookies
    if(loginForm.remember === true) {
      localStorage.setItem('username', loginForm.username) // 写入Cookies
    } else {
      localStorage.removeItem('username') // 删除Cookies
    }
    isLoggingIn.value = false
    ElMessage.success('登录成功')
    emit('login-success')
}

const handleRegister = async () => {
  if (!validateRegisterForm()) return

    isRegistering.value = true
    const res = await register(registerForm)
    if(res.code !== 200) {
      isRegistering.value = false
      return ElMessage.error(res.message)
    }
    emit('register-success', {
      username: registerForm.username,
      email: registerForm.email
    })
    switchTab('login')
    isRegistering.value = false
}

const handleForgotPassword = async () => {
  if (!validateForgotForm()) return

  try {
    isResetting.value = true
    // 这里替换为实际的API调用
    await mockResetPasswordApi()
    alert('密码重置成功，请使用新密码登录')
    switchTab('login')
  } catch (error) {
    alert(error.message)
  } finally {
    isResetting.value = false
  }
}

const handleEmailLogin = async () => {
  if (!validateEmailLoginForm()) return

  try {
    isEmailLoggingIn.value = true
    // 这里替换为实际的API调用
    await mockEmailLoginApi()
    emit('login-success', {
      email: emailLoginForm.email
    })
    closeModal()
  } catch (error) {
    alert(error.message)
  } finally {
    isEmailLoggingIn.value = false
  }
}

// 获取验证码
const getVerificationCode = async (type) => {
  let email = ''

  if (type === 'register') {
    if (!registerForm.email) {
      registerErrors.email = '请输入邮箱'
      return
    } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(registerForm.email)) {
      registerErrors.email = '请输入有效的邮箱地址'
      return
    }
    email = registerForm.email
  } else if (type === 'forgot') {
    if (!forgotForm.email) {
      forgotErrors.email = '请输入邮箱'
      return
    } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(forgotForm.email)) {
      forgotErrors.email = '请输入有效的邮箱地址'
      return
    }
    email = forgotForm.email
  } else if (type === 'emailLogin') {
    if (!emailLoginForm.email) {
      emailLoginErrors.email = '请输入邮箱'
      return
    } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(emailLoginForm.email)) {
      emailLoginErrors.email = '请输入有效的邮箱地址'
      return
    }
    email = emailLoginForm.email
  }
    isGettingCode.value = true
    const res = await getEmailCode(email)
    if (res.code === 200) {
      ElMessage.success('验证码已发送，请注意查收')
    } else {
      ElMessage.error(res.message)
    }
    //设置定时器 60秒后自动打开验证码获取按钮
    setTimeout(() => {
      isGettingCode.value = false
    }, 60000)
}

// 重置所有表单
const resetAllForms = () => {
  loginForm.username = ''
  loginForm.password = ''
  loginForm.remember = false

  registerForm.username = ''
  registerForm.email = ''
  registerForm.code = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''

  forgotForm.email = ''
  forgotForm.code = ''
  forgotForm.newPassword = ''

  emailLoginForm.email = ''
  emailLoginForm.code = ''

  // 清空错误信息
  Object.keys(loginErrors).forEach(key => loginErrors[key] = '')
  Object.keys(registerErrors).forEach(key => registerErrors[key] = '')
  Object.keys(forgotErrors).forEach(key => forgotErrors[key] = '')
  Object.keys(emailLoginErrors).forEach(key => emailLoginErrors[key] = '')
}

// 关闭模态框
const closeModal = () => {
  resetAllForms()
  emit('close')
}
//载入时候获取记住我的用户名
onMounted(() => {
  const username = localStorage.getItem('username')
  if (username) {
    loginForm.username = username
    loginForm.remember = true
  }
  refreshCaptcha()
})
</script>

<style scoped>
.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: opacity 0.3s ease;
}

.modal-container {
  width: 450px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
  transition: all 0.3s ease;
  overflow: hidden;
}

.modal-header {
  padding: 20px;
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: white;
  cursor: pointer;
  padding: 0;
}

.modal-body {
  padding: 20px;
}

.tab-switch {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.tab-switch button {
  padding: 8px 16px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-switch button.active {
  color: #409eff;
  font-weight: bold;
}

.tab-switch button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #555;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  border-color: #409eff;
  outline: none;
}

.input-with-btn {
  display: flex;
  gap: 10px;
}

.input-with-btn input {
  flex: 1;
}

.get-code-btn {
  padding: 0 15px;
  background-color: #f5f7fa;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
}

.get-code-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.input-error {
  border-color: #f56c6c !important;
}

.error-msg {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 14px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.remember-me input {
  margin: 0;
}

.form-actions {
  margin-top: 30px;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #66b1ff;
}

.submit-btn:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.form-footer a {
  color: #409eff;
  text-decoration: none;
}

.form-footer a:hover {
  text-decoration: underline;
}

.divider {
  margin: 0 10px;
  color: #ddd;
}
</style>